package models

import (
	"github.com/astaxie/beego/orm"
	"time"
)

/**
* 公告结构体
*/
type Notice struct {
	Id	        int64   `orm:"column(id);pk"`  //设置主键
	Content     string
	Time        string
}

/**
 * 获取公告
 */
func GetNoticeList() ([]Notice, error) {
	var Notice []Notice
	_,err := NoticeObj().OrderBy("-Time").Limit(5).All(&Notice)
	if err != nil {
		log := UitlLog()
		log.Error("connect db err"+err.Error())
		return nil, err
	}

	return Notice, nil
}
/**
 * 获取最新的公告
 */
func GetNewNotice() ([]Notice, error) {
	var Notice []Notice
	err := NoticeObj().OrderBy("-Time").One(&Notice)
	if err != nil {
		log := UitlLog()
		log.Error("connect db err"+err.Error())
		return nil, err
	}

	return Notice, nil
}
/**
 * 存储公告
 */
func AddNotice(content string ) (*Notice, error) {
	o := orm.NewOrm()
	timeNow := time.Now()
	cr_time := timeNow.Format("2006-01-02 15:04:05")
	notice := &Notice{Content:content,Time:cr_time}
	//存入点赞
	_, err := o.Insert(notice)
	if err != nil{
		log := UitlLog()
		log.Error("connect db err"+err.Error())
		return nil, err
	}

	return notice, nil
}
/**
 * 根据ID取消公告
 */
func DelNotice(id int64) (int64, error) {
	num,err := NoticeObj().Filter("Id",id).Delete()
	if err != nil {
		log := UitlLog()
		log.Error("connect db err"+err.Error())
		return 0, err
	}
	return num, nil
}

/**
 * 根据ID置顶公告
 */
func UpNotice(id int64) (int64, error) {
	timeNow := time.Now()
	up_time := timeNow.Format("2006-01-02 15:04:05")
	num,err := NoticeObj().Filter("Id",id).Update(orm.Params{
		"Time":up_time,
	 })
	if err != nil {
		log := UitlLog()
		log.Error("connect db err"+err.Error())
		return 0, err
	}
	return num, nil
}
/**
 *  Notice 表实例化
 */
func NoticeObj() orm.QuerySeter {
	return orm.NewOrm().QueryTable(new(Notice))
}
